#!/usr/bin/env python3.11
# -*- encoding: utf-8 -*-
"""
@File    :   add_mask.py
@Time    :   2024/09/03 08:22:18
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib

import os
from PIL import Image, ImageEnhance, ImageDraw, ImageFont


def add_mask(img_path, save_path):
    img = Image.open(img_path)
    # 底图背景
    layer1 = img.convert("RGBA")

    # 使用img的亮度
    r, g, b, a = layer1.split()
    # 根据layer1的大小生产一个黑色透明的图层
    layer2 = Image.new("RGBA", layer1.size, (0, 0, 0, 0))

    # opacity为透明度，范围(0,1)
    opacity = 0.55
    alpha = ImageEnhance.Brightness(a).enhance(opacity)
    layer2.putalpha(alpha)

    # 使用alpha_composite叠加，两者需相同size
    final = Image.new("RGBA", layer1.size)
    final = Image.alpha_composite(final, layer1)
    final = Image.alpha_composite(final, layer2)
    # 保存图片
    final.save(save_path)
    
def add_loading(img_path, save_path):
    img = Image.open(img_path)
    width, height = img.size
    # 尝试加载字体，如果失败则使用默认字体
    try:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        font_path = os.path.join(script_dir, "ComicSansMS3.ttf")
        font = ImageFont.truetype(font=font_path, size=20)
    except IOError:
        font = ImageFont.load_default()
    # 绘制文字
    draw = ImageDraw.Draw(img)
    draw.text((width / 2 - 30, height - 40), "Loading...", font=font,fill=(255, 255, 255))
    img.save(save_path)


if __name__ == "__main__":
    # 获取当前文件的绝对路径
    current_file_path = os.path.abspath(__file__)
    # 获取当前文件所在的目录
    current_dir = os.path.dirname(current_file_path)
    # 获取当前文件夹的上级目录
    parent_dir = os.path.dirname(current_dir)
    # 定位到上级目录下的某个文件
    path = os.path.join(parent_dir, "Img/cover.png")
    save_path = os.path.join(parent_dir, "Img/loading.png")
    img = Image.open(path)
    # 输出图片的尺寸
    print(img.size)
    # 输出图片的格式
    print(img.format)
    add_mask(path, save_path)
    add_loading(save_path,save_path)